package com.jinzhi.jzweb.controller;


import java.util.*;

import com.jinzhi.common.domain.Tree;
import com.jinzhi.common.utils.BuildTree;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-07-08 11:44:50 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/papersDeployment")
public class PapersDeploymentController extends BaseController {
	@Autowired
	private PapersDeploymentService papersDeploymentService;
    @Autowired
    private UserService userService;
    @Autowired
    private TeachingMajorService teachingMajorService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CoursesService  coursesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private MajorItemBankService majorItemBankService;

    @GetMapping()
	@RequiresPermissions("jzweb:papersDeployment:papersDeployment")
	String PapersDeployment(){
	    return "jzweb/papersDeployment/papersDeployment";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:papersDeployment:papersDeployment")
	public Result<Page<PapersDeploymentDO>> list(PapersDeploymentDO papersDeploymentDTO){

		// 查询列表数据
		Page<PapersDeploymentDO> page = papersDeploymentService.selectPage(getPage(PapersDeploymentDO.class),
					papersDeploymentService.convertToEntityWrapper().orderBy("id", false));
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			PapersDeploymentDO obj = (PapersDeploymentDO) page.getRecords().get(i);
            UserDO userDO = userService.selectById(obj.getCreaterId());
            if(userDO!=null && userDO.getUsername()!=null){
                obj.setCreaterName(userDO.getUsername());
            }else {
                obj.setCreaterName("");
            }
            //教学专业名称
            TeachingMajorDO teachingMajorDO = teachingMajorService.selectById(obj.getTeacherMajorId());
            if(teachingMajorDO!=null && teachingMajorDO.getName()!=null){
                obj.setTeacherMajorName(teachingMajorDO.getName());
            }else {
                obj.setTeacherMajorName("");
            }
            //班级名称
            StudentClassesDO studentClassesDO = classesService.selectById(obj.getClassId());
            if(studentClassesDO!=null && studentClassesDO.getName()!=null){
                obj.setStudentclassName(studentClassesDO.getName());
            }else {
                obj.setStudentclassName("");
            }
            //课程名称
            CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
            if(coursesDO!=null && coursesDO.getName()!=null){
                obj.setCourseName(coursesDO.getName());
            }else {
                obj.setCourseName("");
            }
            //机构名称
            OrganizationNewsDO org = organizationNewsService.selectById(obj.getOrgId());
            if(org!=null && org.getName()!=null){
                obj.setOrgName(org.getName());
            }else {
                obj.setOrgName("");
            }

            list.add(obj);
		}
		//用来防止前端页面一直显示加载数据
        //if(list.size()>0) {
            page.setRecords(list);
        /*}else {
            page.setRecords(null);
        }*/
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:papersDeployment:add")
	String add(Model model){
        Wrapper<TeachingMajorDO> wrapper = new EntityWrapper<TeachingMajorDO>().orderBy("id", false);

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                wrapper.eq("creater_id",this.getUserId());
            }
        }

        if (!roleName.contains("超级用户角色")) {
            List<Map<Object,Object>> list = new ArrayList<>();
            Map<Object,Object> map1 = new HashMap();
            map1.put("id",this.getUser().getOrgId());
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
            if(organizationNewsDO != null){
                map1.put("name",organizationNewsDO.getName());
            }else{
                map1.put("name",this.getUser().getOrgName());
            }
            list.add(map1);
            model.addAttribute("orgNews",list);
        } else {
            model.addAttribute("orgNews",organizationRolesService.selByRoleType(0));
        }

        List<TeachingMajorDO> teachingMajorDOS = teachingMajorService.selectList(wrapper);
        model.addAttribute("teachingMajor",teachingMajorDOS);
	    return "jzweb/papersDeployment/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:papersDeployment:edit")
	String edit(@PathVariable("id") Long id,Model model){
        Wrapper<TeachingMajorDO> wrapper = new EntityWrapper<TeachingMajorDO>().orderBy("id", false);

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                wrapper.eq("creater_id",this.getUserId());
            }
        }
        List<TeachingMajorDO> teachingMajorDOS = teachingMajorService.selectList(wrapper);
        model.addAttribute("teachingMajor",teachingMajorDOS);

        if (!roleName.contains("超级用户角色")) {
            List<Map<Object,Object>> list = new ArrayList<>();
            Map<Object,Object> map1 = new HashMap();
            map1.put("id",this.getUser().getOrgId());
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
            if(organizationNewsDO != null){
                map1.put("name",organizationNewsDO.getName());
            }else{
                map1.put("name",this.getUser().getOrgName());
            }
            list.add(map1);
            model.addAttribute("orgNews",list);
        } else {
            model.addAttribute("orgNews",organizationRolesService.selByRoleType(0));
        }

		PapersDeploymentDO papersDeployment = papersDeploymentService.selectById(id);
		model.addAttribute("papersDeployment", papersDeployment);
	    return "jzweb/papersDeployment/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:papersDeployment:add")
	public Result<String> save( PapersDeploymentDO papersDeployment){
        papersDeployment.setCreaterDate(new Date());
        papersDeployment.setCreaterId(this.getUserId());
		papersDeploymentService.insert(papersDeployment);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:papersDeployment:edit")
	public Result<String>  update( PapersDeploymentDO papersDeployment){
		boolean update = papersDeploymentService.updateById(papersDeployment);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:papersDeployment:remove")
	public Result<String>  remove( Long id){
		papersDeploymentService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:papersDeployment:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		papersDeploymentService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

    @Log("查询菜单树形数据")
    @GetMapping("/tree")
    @ResponseBody
    Tree<MajorItemBankDO> tree(String id, String teacher_major_id) {
        Tree<MajorItemBankDO> tree = new Tree<MajorItemBankDO>();
        List<Tree<MajorItemBankDO>> trees = new ArrayList<Tree<MajorItemBankDO>>();
        Wrapper<MajorItemBankDO> wrapper = new EntityWrapper<MajorItemBankDO>().orderBy("type", true);
        PapersDeploymentDO paper = null;
        if(id!=null && !id.equals("")){
            paper = papersDeploymentService.selectById(Long.valueOf(id));
        }
        if(teacher_major_id!=null && !teacher_major_id.equals("")){
            wrapper.eq("teacher_major_id", teacher_major_id);
        }

        List<MajorItemBankDO> majorItemBankDOS = majorItemBankService.selectList(wrapper);
        for (MajorItemBankDO m : majorItemBankDOS) {
            Tree<MajorItemBankDO> t1 = new Tree<MajorItemBankDO>();
            t1.setId(m.getId().toString());
            if(paper!=null) {
                boolean isHave = false;
                if(paper.getItems()!=null){
                    //System.out.println("paper.getItems():"+paper.getItems());
                    String[] idLlist = paper.getItems().split(",");
                    if(idLlist.length>0){
                        for (int a=0; a<idLlist.length; a++){
                            /*System.out.println("idLlist[a]:"+idLlist[a]);
                            System.out.println("m.getId():"+(m.getId()+""));
                            System.out.println(idLlist[a].equals(m.getId()+""));*/
                            if(idLlist[a].equals(m.getId()+"")){
                                isHave = true;
                                break;
                            }
                        }
                    }
                }
               // System.out.println("isHave:"+isHave);
                if(isHave) {
                    Map<String, Object> state = new HashMap<>(16);
                    state.put("selected", true);
                    t1.setState(state);
                }
            }
            String textStr="";
            if(m.getType()==0) {
                textStr += "单选题---";
            }else if(m.getType()==1) {
                textStr += "多选题---";
            }else if(m.getType()==2) {
                textStr += "判断题---";
            }else if(m.getType()==3) {
                textStr += "填空题---";
            }else if(m.getType()==4) {
                textStr += "问答题---";
            }
            if(m.getTopicContent().length()>60) {
                textStr += m.getTopicContent().substring(0,60)+"...";
            }else {
                textStr += m.getTopicContent();
            }
            t1.setText(textStr);

            trees.add(t1);
        }

        Tree<MajorItemBankDO> t = BuildTree.build(trees);
        tree = t;
        return tree;
    }
}
